/*************************************************************************
 > File Name   : index.js
 > Author      : zhoutk
 > Mail        : zhoutk@189.cn
 > Created Time: 2015-05-28 18:34
 ************************************************************************/

var http = require('http');
var restrouter = require('./router');
var restparser = require('./restparser');
var parse = require('url').parse;

http.createServer(function (req, res) {
    var url = parse(req.url), pathname = url.pathname;

    console.log('Request URL: http://localhost' + url.href);
    //解析URL参数到resource对象
    req.resource = restparser.parse(pathname);
    //resource.id 存在，表示是RESTful的请求
    if(req.resource.id){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        restrouter.router(req, res, function(result){
            var stringfyResult = JSON.stringify(result);
            res.end(stringfyResult);
        });
    }else{
        res.writeHead(200, {'Content-Type': 'text/plain'});
        console.log('Request URL is not in RESTful style!');
        res.end('Request URL is not in RESTful style!');
    }
}).listen(80, 'localhost');
console.log('Server running at http://localhost/');
